<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 供应商管理
 *
 * @icon fa fa-truck
 * @remark 管理供应商信息及评级
 */
class Supplier extends Backend
{
    /**
     * Supplier模型对象
     * @var \app\admin\model\scanwork\Supplier
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\Supplier;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("levelList", $this->model->getLevelList());
        $this->view->assign("categoryList", $this->model->getCategoryList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                
                // 自动生成供应商编码
                if (empty($params['code'])) {
                    $params['code'] = $this->generateSupplierCode();
                }
                
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    // 检查是否有关联的物料报价
                    $materialCount = \app\admin\model\scanwork\MaterialSupplier::where('supplier_id', $item->id)->count();
                    if ($materialCount > 0) {
                        throw new Exception("供应商【{$item->name}】还有{$materialCount}个物料报价，请先删除相关报价");
                    }
                    
                    // 检查是否有关联的采购记录
                    $purchaseCount = \app\admin\model\scanwork\PurchaseRecord::where('supplier_id', $item->id)->count();
                    if ($purchaseCount > 0) {
                        throw new Exception("供应商【{$item->name}】还有{$purchaseCount}条采购记录，无法删除");
                    }
                    
                    $count += $item->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        } else {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }

    /**
     * 查看供应商详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取供应的物料清单
        $materials = \app\admin\model\scanwork\MaterialSupplier::with(['material'])
            ->where('supplier_id', $ids)
            ->where('status', 1)
            ->select();
        
        // 获取采购历史
        $purchases = \app\admin\model\scanwork\PurchaseRecord::with(['material', 'order'])
            ->where('supplier_id', $ids)
            ->order('createtime', 'desc')
            ->limit(10)
            ->select();
        
        // 统计数据
        $totalPurchaseAmount = \app\admin\model\scanwork\PurchaseRecord::where('supplier_id', $ids)->sum('total_amount');
        $materialCount = count($materials);
        $purchaseCount = \app\admin\model\scanwork\PurchaseRecord::where('supplier_id', $ids)->count();
        
        $this->view->assign('row', $row);
        $this->view->assign('materials', $materials);
        $this->view->assign('purchases', $purchases);
        $this->view->assign('totalPurchaseAmount', $totalPurchaseAmount);
        $this->view->assign('materialCount', $materialCount);
        $this->view->assign('purchaseCount', $purchaseCount);
        
        return $this->view->fetch();
    }

    /**
     * 生成供应商编码
     */
    private function generateSupplierCode()
    {
        $prefix = 'SUP';
        $count = $this->model->count();
        $code = $prefix . str_pad($count + 1, 4, '0', STR_PAD_LEFT);
        
        // 检查是否重复
        while ($this->model->where('code', $code)->count() > 0) {
            $count++;
            $code = $prefix . str_pad($count + 1, 4, '0', STR_PAD_LEFT);
        }
        
        return $code;
    }
}

